package me.siphone.sip;

import androidx.annotation.NonNull;
import java.util.Locale;
import org.linphone.LinphoneContext;
import org.linphone.LinphoneManager;
import org.linphone.core.AccountCreator;
import org.linphone.core.AuthInfo;
import org.linphone.core.Core;
import org.linphone.core.CoreListener;
import org.linphone.core.CoreListenerStub;
import org.linphone.core.ProxyConfig;
import org.linphone.core.RegistrationState;
import org.linphone.core.TransportType;
import org.linphone.core.tools.Log;
import org.linphone.settings.LinphonePreferences;

public class SipUtil {

    private static String activeCallNumber;

    private static RegistrationState state;

    private static final CoreListener coreListener =
            new CoreListenerStub() {
                @Override
                public void onRegistrationStateChanged(
                        @NonNull Core core,
                        @NonNull ProxyConfig proxyConfig,
                        RegistrationState state,
                        @NonNull String message) {
                    super.onRegistrationStateChanged(core, proxyConfig, state, message);
                    SipUtil.state = state;
                }
            };

    public static boolean isRegister() {
        return SipUtil.state == RegistrationState.Ok;
    }

    public static void registerListener() {
        Core core = LinphoneManager.getCore();
        if (core != null) {
            core.removeListener(coreListener);
            core.addListener(coreListener);
        }
    }

    public static void createAccount(
            String domain,
            TransportType transport,
            String username,
            String password,
            String displayName) {
        Core core = LinphoneManager.getCore();
        if (core != null) {
            Log.i("[Generic Connection Assistant] Reloading configuration with default");
            reloadDefaultAccountCreatorConfig();
        }

        AccountCreator accountCreator = getAccountCreator();
        accountCreator.setUsername(username);
        accountCreator.setDomain(domain);
        accountCreator.setPassword(password);
        accountCreator.setDisplayName(displayName);
        accountCreator.setTransport(transport);

        createProxyConfigAndLeaveAssistant();
    }

    public static void setDefaultSettings() {
        // 默认设置
        LinphonePreferences.instance().setDebugEnabled(true);
        LinphonePreferences.instance().setJavaLogger(true);
        LinphonePreferences.instance().enableAutoAnswer(true);
        LinphonePreferences.instance().setAutoAnswerTime(0);
    }

    public static void removeAllAccount() {
        Core core = LinphoneManager.getCore();
        if (core != null) {
            ProxyConfig[] proxyConfigs = core.getProxyConfigList();
            for (ProxyConfig proxyConfig : proxyConfigs) {
                core.removeProxyConfig(proxyConfig);
                AuthInfo authInfo = proxyConfig.findAuthInfo();
                if (authInfo != null) {
                    Log.d("移除账户：" + authInfo.getUsername());
                    core.removeAuthInfo(authInfo);
                }
            }
        }
    }

    public static void saveActiveCallNumber(String number) {
        activeCallNumber = number;
    }

    public static String getActiveCallNumber() {
        return activeCallNumber;
    }

    public static String getActiveAuthNumber() {
        Core core = LinphoneManager.getCore();
        if (core != null && core.getAuthInfoList().length > 0) {
            return core.getAuthInfoList()[0].getUsername();
        }
        return "";
    }

    static void reloadDefaultAccountCreatorConfig() {
        Log.i("[Assistant] Reloading configuration with default");
        reloadAccountCreatorConfig(LinphonePreferences.instance().getDefaultDynamicConfigFile());
    }

    static void reloadAccountCreatorConfig(String path) {
        Core core = LinphoneManager.getCore();
        if (core != null) {
            core.loadConfigFromXml(path);
            AccountCreator accountCreator = getAccountCreator();
            accountCreator.reset();
            accountCreator.setLanguage(Locale.getDefault().getLanguage());
        }
    }

    private static AccountCreator getAccountCreator() {
        return LinphoneManager.getInstance().getAccountCreator();
    }

    static void createProxyConfigAndLeaveAssistant() {
        ProxyConfig proxyConfig = getAccountCreator().createProxyConfig();
        if (proxyConfig != null) {
            proxyConfig.setPushNotificationAllowed(false);
        }
        Log.w("[Assistant] Unknown domain used, push probably won't work, enable service mode");
        LinphonePreferences.instance().setServiceNotificationVisibility(true);
        LinphoneContext.instance().getNotificationManager().startForeground();

        LinphonePreferences.instance().setPushNotificationEnabled(false);

        if (proxyConfig == null) {
            Log.e("[Assistant] Account creator couldn't create proxy config");
            // TODO: display error message
        } else {

            proxyConfig.setDialPrefix("");

            LinphonePreferences.instance().firstLaunchSuccessful();
        }
    }
}
